#pragma once

#include <iostream>
#include <functional>
#include <unordered_map>
#include <ctime>
#include <sys/types.h>
#include <unistd.h>

using task_t = std::function<void()>;

void Download()
{
    std::cout << "我是下载任务..., pid:" << getpid() << std::endl;
}

void Log()
{
    std::cout << "我是日志任务..., pid:" << getpid() << std::endl;
}

void Sql()
{
    std::cout << "我是数据库同步任务..., pid:" << getpid() << std::endl;
}

static int number = 0;
class TaskManger
{
public:
    TaskManger()
    {
        InsertTask(Download);
        InsertTask(Log);
        InsertTask(Sql);
    }

    // 插入任务
    void InsertTask(task_t t)
    {
        tasks[number++] = t;
    }

    // 选择任务
    int SelectTask()
    {
        return rand() % number;
    }

    // 执行任务
    void Excute(int number)
    {
        if (tasks.find(number) == tasks.end())
            return;
        tasks[number]();
    }

    ~TaskManger() {}

private:
    std::unordered_map<int, task_t> tasks;
};

TaskManger tm;

void Worker()
{
    // read -> 0 子进程从标准输入上读取数据
    while (true)
    {
        int cmd = 0;
        int n = ::read(0, &cmd, sizeof(cmd));
        if (n == sizeof(cmd))
        {
            tm.Excute(cmd);
        }
        else if (n == 0)
        {
            std::cout << "pid: " << getpid() << "quit..." << std::endl;
            break;
        }
        else
        {
        }
    }
}
